package com.demo.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.demo.domain.Admin;
import com.demo.repository.AdminRepository;
import com.demo.service.AdminService;
import com.demo.util.SqlUtils;
import com.demo.util.StringUtil;
import com.mdx.mobile.commons.verfy.Md5;

@Service
public  class AdminServiceImpl implements AdminService{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private AdminRepository adminRepository;

	@Override
	public List<Admin> findByUserNameAndPwd(String userName, String password) {
		// TODO Auto-generated method stub
		String sql = "select * from r_admin where username=? and password = ? and state = 1";
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,new Object[]{userName,password});
		List<Admin> ret = new ArrayList<>();
		for (Map<String, Object> map : result) {
			Admin admin = new Admin();
			admin.setCreateTime((Date)map.get("create_time"));
			admin.setModifyTime((Date)map.get("modify_time"));
			admin.setId((String)map.get("id"));
//			admin.setPassword((String)map.get("password"));
			admin.setRoleCode((String)map.get("role_code"));
			admin.setState(1);
			admin.setUsername((String)map.get("username"));
			ret.add(admin);
		}
		
		return ret;
	}

	@Override
	public Admin create(Admin admin) {
		// TODO Auto-generated method stub
		admin.setCreateTime(new Date());
		admin.setModifyTime(new Date());
		if(StringUtils.isBlank(admin.getRoleCode())){
			admin.setRoleCode("ADMIN");
		}
		admin.setId(StringUtil.getUUID());
		try {
			admin.setPassword(Md5.md5(admin.getPassword()));
		} catch (Exception e) {
			return null;
		}
		admin.setState(1);
		return adminRepository.save(admin);
	}

	@Override
	public Page<Admin> findByRoleCode(String roleCode, Pageable p) {
		// TODO Auto-generated method stub
		return adminRepository.findByRoleCode(roleCode, p);
	}

	@Override
	public int updateByPrimaryKeySelective(Admin admin) {
		// TODO Auto-generated method stub
		try {
			String sql = SqlUtils.update(admin, true, " where id = '"+admin.getId()+"'");
			return jdbcTemplate.update(sql);
		}catch (Exception e) {
			return 0;
		}
	}

	@Override
	public Admin findOne(String id) {
		// TODO Auto-generated method stub
		return adminRepository.findOne(id);
	}

	@Override
	public Admin findByAccount(String account) {
		// TODO Auto-generated method stub
		Collection<Admin> list = adminRepository.findByUsername(account);
		if(list.size()>0) return list.iterator().next();
		return null;
	}


}
